package com.frank.service.test3;

import java.nio.ByteBuffer;

import static com.frank.util.ByteBufferUtil.debugAll;

/**
 * @Author: huweifeng
 * @Date: 2024/12/11
 * @Description: 测试粘包、半包
 * - Hello,world\nI'm zhangsan\nHo
 * - w are you?\n
 * 目的：将错乱的数据恢复成原始的按照\n分割的数据
 **/
public class TestByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);

        source.put("w are you?\n".getBytes());
        split(source);
    }

    // 思路：一个一个字节的读
    private static void split(ByteBuffer source) {
        // 切换为读模式
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                // 长度处理很关键
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从source读，向target写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                // 打印字符
                debugAll(target);
            }
        }
        source.compact();
    }
}
